
<template>
  <div class="comment-container">      
        <h4>发表评论</h4>
        <hr>
        <textarea placeholder="请输入要评论的内容" v-model="msg"></textarea>
        <mt-button type="primary" size="large" @click="postComment">发表评论</mt-button>

    <div class="comment-list" v-for="(item,i) in commentInfo" :key="item.add_time">
      <div class="comment-item">
        <div class="comment-title">第{{ i + 1 }}楼&nbsp;&nbsp;用户：{{ item.user_name }}&nbsp;&nbsp;发表时间：{{ item.add_time | dateFormat}}</div>
        <div class="comment-content">
          {{ item.content }}
        </div>
      </div>
    </div>  

    <mt-button type="danger" size="large" plain @click="getMore">加载更多</mt-button>

  </div>
</template>


<script>
import { Toast } from "mint-ui";    

    export default {
      data() {
        return {
          pageIndex: 1,
          commentInfo: [],
          msg: ''
        }
      },
      created() {
        this.getComment();        
      },
      methods: {
        getComment() {
          this.$http.get("api/getcomments/"+ this.id+ "?pageindex="+ this.pageIndex).then(result=> {
             if(result.body.status === 0) {
               //console.log(result.body);
               //this.commentInfo = result.body.message;

               this.commentInfo = this.commentInfo.concat(result.body.message);
             }else {
               Toast("获取评论失败！");
             }
          })
        },
        //鼠标点击按钮触发事件
        getMore() {
          this.pageIndex ++;
          this.getComment();
        },
        //鼠标点击按钮触发事件
        postComment() {
          //发表内容不能为空
          if(this.msg.trim().length==0) {
            return Toast("发表内容不能为空！");
          }

          //参数1：请求的地址  参数2：提交的数据  参数3：发送给服务器数据的表单格式
          this.$http.post("api/postcomment/"+ this.id, {content: this.msg.trim()}).then(result=> {
            if(result.body.status === 0) {
              this.commentInfo.unshift({
                user_name: "匿名用户",
                add_time: Date.now(),
                content: this.msg
              });
              this.msg = "";
            }else {
              Toast("发表评论失败！");
            }
          })
        }
      },
      props: ["id"]  //拿到父组件传递过来的id  属性绑定传值
    }
</script>

<style lang="scss" scoped>
.comment-container {
  textarea {
    margin: 0;
    font-size: 14px;
  }

  .comment-list {
    .comment-item {
      font-size: 14px;
      .comment-title {
        background-color: #ccc;
        line-height: 30px;
      }
      .comment-content {
        text-indent: 2em;
        line-height: 35px;
      }
    }
  }
}
</style>
